import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Popconfirm, Card, Tag, Tabs } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SettingOutlined, FileTextOutlined } from '@ant-design/icons';
import { api } from '../utils/api';

const { TabPane } = Tabs;

interface Config {
  id: number;
  config_key: string;
  config_value: string;
  description: string;
}

interface Log {
  id: number;
  action: string;
  description: string;
  admin_id: number;
  created_at: string;
}

const SystemSettings: React.FC = () => {
  const [configs, setConfigs] = useState<Config[]>([]);
  const [logs, setLogs] = useState<Log[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingConfig, setEditingConfig] = useState<Config | null>(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [logPagination, setLogPagination] = useState({ current: 1, pageSize: 10, total: 0 });

  useEffect(() => { fetchConfigs(); }, [pagination.current, pagination.pageSize]);
  useEffect(() => { fetchLogs(); }, [logPagination.current, logPagination.pageSize]);

  const fetchConfigs = async () => {
    try {
      setLoading(true);
      const response = await api.get('/system/configs', {
        params: { page: pagination.current, per_page: pagination.pageSize }
      });
      if (response.data.success) {
        setConfigs(response.data.data.items);
        setPagination(prev => ({ ...prev, total: response.data.data.total }));
      }
    } catch (error) {
      message.error('获取配置失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchLogs = async () => {
    try {
      setLoading(true);
      const response = await api.get('/system/logs', {
        params: { page: logPagination.current, per_page: logPagination.pageSize }
      });
      if (response.data.success) {
        setLogs(response.data.data.items);
        setLogPagination(prev => ({ ...prev, total: response.data.data.total }));
      }
    } catch (error) {
      message.error('获取日志失败');
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (record: Config) => {
    setEditingConfig(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await api.delete(`/system/configs/${id}`);
      message.success('删除成功');
      fetchConfigs();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingConfig) {
        await api.put(`/system/configs/${editingConfig.config_key}`, values);
        message.success('更新成功');
      } else {
        await api.post('/system/configs', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchConfigs();
    } catch (error) {
      message.error(editingConfig ? '更新失败' : '创建失败');
    }
  };

  const configColumns = [
    { title: '配置键', dataIndex: 'config_key', key: 'config_key', width: 180 },
    { title: '配置值', dataIndex: 'config_value', key: 'config_value', width: 200 },
    { title: '描述', dataIndex: 'description', key: 'description', width: 300 },
    { title: '操作', key: 'action', width: 150, render: (_: any, record: Config) => (
      <Space size="small">
        <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
        <Popconfirm title="确定要删除该配置吗？" onConfirm={() => handleDelete(record.id)} okText="确定" cancelText="取消">
          <Button type="link" danger icon={<DeleteOutlined />}>删除</Button>
        </Popconfirm>
      </Space>
    ) }
  ];

  const logColumns = [
    { title: '操作', dataIndex: 'action', key: 'action', width: 120 },
    { title: '描述', dataIndex: 'description', key: 'description', width: 300 },
    { title: '管理员ID', dataIndex: 'admin_id', key: 'admin_id', width: 100 },
    { title: '时间', dataIndex: 'created_at', key: 'created_at', width: 180 }
  ];

  return (
    <div>
      <Tabs defaultActiveKey="configs">
        <TabPane tab={<span><SettingOutlined />系统配置</span>} key="configs">
          <Card title="系统配置" extra={<Button type="primary" icon={<PlusOutlined />} onClick={() => { setEditingConfig(null); form.resetFields(); setModalVisible(true); }}>新建配置</Button>}>
            <Table
              columns={configColumns}
              dataSource={configs}
              rowKey="id"
              loading={loading}
              pagination={{
                ...pagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
              }}
              onChange={(pagination) => {
                setPagination(prev => ({ ...prev, current: pagination.current || 1, pageSize: pagination.pageSize || 10 }));
              }}
            />
          </Card>
        </TabPane>
        <TabPane tab={<span><FileTextOutlined />操作日志</span>} key="logs">
          <Card title="操作日志">
            <Table
              columns={logColumns}
              dataSource={logs}
              rowKey="id"
              loading={loading}
              pagination={{
                ...logPagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
              }}
              onChange={(pagination) => {
                setLogPagination(prev => ({ ...prev, current: pagination.current || 1, pageSize: pagination.pageSize || 10 }));
              }}
            />
          </Card>
        </TabPane>
      </Tabs>
      <Modal
        title={editingConfig ? '编辑配置' : '新建配置'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item name="config_key" label="配置键" rules={[{ required: true, message: '请输入配置键' }]}> <Input /> </Form.Item>
          <Form.Item name="config_value" label="配置值" rules={[{ required: true, message: '请输入配置值' }]}> <Input /> </Form.Item>
          <Form.Item name="description" label="描述"> <Input /> </Form.Item>
          <Form.Item> <Space> <Button type="primary" htmlType="submit">{editingConfig ? '更新' : '创建'}</Button> <Button onClick={() => setModalVisible(false)}>取消</Button> </Space> </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SystemSettings; 